package com.fz.song.config;


import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定义配置
        http.authorizeRequests()
                //定义资源和角色
                //添加ant模式的配置,
                // ?匹配任意单个字符，使用*匹配0或任意数量的字符，使用**匹配0或者更多的目录。
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").permitAll()
                //链式调用的and()返回HttpSecurity,相当于返从这个开始新的配置
                .and()
                .formLogin()

                .and()
                //session的配置
                .sessionManagement()
                .sessionFixation()
                //过期策略
                .none()
                //session   过期后跳转路径
                //.invalidSessionUrl("/invalidsession.html")
                .invalidSessionStrategy(new InvalidSessionStrategy() {
                    @Override
                    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = null;
                        try {
                            writer = response.getWriter();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        writer.write("{\"code\": \"-1\",\"msg\": \"session  过期\"}");
                        writer.flush();
                        writer.close();
                    }
                })
                .maximumSessions(1);
                //当会话数量达到最大值的时候,阻止新的会话创建
                //.maxSessionsPreventsLogin(true);
    }
}
